using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace Framework.Helper
{
    public static class AssetBundleHelper
    {
        public static readonly string abextension = ".ab";

        public static readonly byte abOffset = 1;

        public static async UniTask<AssetBundle> LoadAssetBundleAsync(string assetPath, bool withEncode = true)
        {
            try
            {
                UnityWebRequest request = UnityWebRequest.Get(assetPath);
                await request.SendWebRequest();
                
                if (request.result != UnityWebRequest.Result.Success)
                    return null;
                
                byte[] results = request.downloadHandler.data;
                if (abOffset > 0 && withEncode)
                {
                    ConvertAssetBundleBytes(results, out byte[] data);
                    results = data;
                }
                
                return AssetBundle.LoadFromMemory(results);
            }
            catch (Exception e)
            {
                // Debug.LogError($"can not load assetbundle at path: {assetPath}");
                return null;
            }
        }
    
        public static AssetBundle LoadBundleSync(string assetPath)
        {
            return AssetBundle.LoadFromFile(assetPath, 0, abOffset);
        }
        
        public static AssetBundleCreateRequest LoadBundleAsync(string assetPath)
        {
            try
            {
                AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(assetPath, 0, abOffset);
                return request;
            }
            catch (Exception e)
            {
                Debug.Log($"load assetbundle named: {assetPath} fail. reason: {e.Message}");
                return null;
            }
        }
        
        // 把ab的字节数组转化成头部偏移abOffset长度的字节数组
        public static void ConvertAssetBundleBytes(byte[] src, out byte[] dst)
        {
            // 因打ab时, ab资源头部添加 1byte
            dst = new byte[src.Length - abOffset];
            Array.Copy(src, abOffset, dst, 0, src.Length - abOffset);
        }
    }
}